import React, { Children, createContext, useContext, useState } from "react";
import { MenuDefaultProps, MenuItemProps, MenuProps, OnSelect } from "./interface";
import classNames from "classnames";
import SubMenu from "./subMenu";

interface IMenuContext {
    index: string;
    onSelect?: OnSelect;
}

export const MenuContext = createContext<IMenuContext>({ index: '0' });

/** 菜单组件UI */
const Menu: React.FC<MenuProps> = (props) => {

    const { defaultIndex = '0', mode, onSelect, className, style, children } = { ...MenuDefaultProps, ...props };

    const [activeIndex, setActiveIndex] = useState(defaultIndex);

    const classes = classNames('kd-menu', className, {
        'kd-menu-vertical': mode === 'vertical'
    })

    // 处理点击MenuItem的回调函数
    function handleSelect(index: string) {
        setActiveIndex(index);
        console.log("点击index:", index);
        if (onSelect) {
            onSelect(index);
        }
    }

    // 要传递给MenuItem的属性
    const passedContext: IMenuContext = {
        index: activeIndex,
        onSelect: handleSelect,
    }

    // 在children中只渲染MenuItem组件
    const renderChildren = () => {
        return Children.map(children, (child, index) => {
            // 检查：child是否为有效的React元素，以及其类型是否为MenuItem
            if (React.isValidElement(child) && (child.type === MenuItem || child.type === SubMenu)) {
                // 增加：自动为MenuItem组件的index属性赋值
                return React.cloneElement(child as React.ReactElement<MenuItemProps>, {index: index + ''});
            } else {
                console.error('Warning: Menu has a child which is not a MenuItem component');
            }
        })
    }

    return (
        // data-testid 是用于配合jest测试中获取元素的依据
        <ul className={classes} style={style} data-testid='test-menu'>
            <MenuContext.Provider value={passedContext}>
                {renderChildren()}
            </MenuContext.Provider>
        </ul>
    )
}

/** 菜单项组件UI */
export const MenuItem: React.FC<MenuItemProps> = (props) => {

    const { index, disabled, className, style, children } = props;

    const { index: activeIndex, onSelect } = useContext(MenuContext);

    const classes = classNames('kd-memu-item', className, {
        'is-disabled': disabled,
        'is-active': (index === activeIndex) && !disabled,
    })

    function handleSelect() {
        // 如果当前MenuItem设置为disable，则无法进行点击事件
        if (onSelect && !disabled && (typeof index === 'string')) {
            onSelect(index);
        }
    }

    return (
        <li className={classes} style={style} onClick={handleSelect}>
            {children}
        </li>
    )
}

export default Menu;

